<template>
  <div class="markdown-preview">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" :size="50">
        <Loading />
      </el-icon>
      <p>Markdown 加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <el-icon :size="80">
        <WarningFilled />
      </el-icon>
      <p>{{ error }}</p>
    </div>

    <el-scrollbar v-else class="markdown-container">
      <div class="markdown-content" v-html="htmlContent"></div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { Loading, WarningFilled } from '@element-plus/icons-vue'
import { readFileContent } from '../../utils/fileHelper'

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
})

const loading = ref(false)
const error = ref('')
const htmlContent = ref('')

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (err) {
        console.error('代码高亮失败:', err)
      }
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true,
  gfm: true
})

// 加载 Markdown 文件
const loadMarkdown = async () => {
  try {
    loading.value = true
    error.value = ''
    htmlContent.value = ''

    let content = ''
    
    // 如果是 URL 文件，使用 fetch
    if (props.file.isUrl) {
      console.log('✓ 使用 URL 加载 Markdown:', props.file.url)
      const response = await fetch(props.file.url)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      content = await response.text()
    } else {
      // 本地文件，使用 FileReader
      console.log('✓ 使用本地文件加载 Markdown')
      content = await readFileContent(props.file.raw, 'text')
    }
    
    // 转换 Markdown 为 HTML
    htmlContent.value = marked(content)
    loading.value = false
  } catch (err) {
    console.error('Markdown 加载失败:', err)
    if (err.message.includes('CORS') || err.message.includes('Failed to fetch')) {
      error.value = 'Markdown 加载失败：CORS 跨域限制。建议：1) 下载后上传 2) 使用代理 URL'
    } else {
      error.value = 'Markdown 文件加载失败：' + err.message
    }
    loading.value = false
  }
}

watch(() => props.file, () => {
  if (props.file) {
    loadMarkdown()
  }
}, { immediate: true })

onMounted(() => {
  if (props.file) {
    loadMarkdown()
  }
})
</script>

<style scoped>
.markdown-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #409EFF;
}

.error-container {
  color: #F56C6C;
}

.loading-container p,
.error-container p {
  margin-top: 16px;
  font-size: 14px;
}

.markdown-container {
  flex: 1;
  overflow: auto;
}

.markdown-content {
  padding: 40px;
  background: #ffffff;
  margin: 20px auto;
  max-width: 900px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-height: calc(100% - 40px);
  line-height: 1.8;
  color: #333;
}

/* Markdown 样式 */
:deep(.markdown-content h1) {
  font-size: 32px;
  font-weight: 600;
  margin: 24px 0 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #eaecef;
}

:deep(.markdown-content h2) {
  font-size: 24px;
  font-weight: 600;
  margin: 20px 0 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid #eaecef;
}

:deep(.markdown-content h3) {
  font-size: 20px;
  font-weight: 600;
  margin: 16px 0 8px;
}

:deep(.markdown-content p) {
  margin: 12px 0;
  line-height: 1.8;
}

:deep(.markdown-content code) {
  background: #f6f8fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 0.9em;
  color: #e83e8c;
}

:deep(.markdown-content pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 16px 0;
}

:deep(.markdown-content pre code) {
  background: none;
  padding: 0;
  color: inherit;
  font-size: 0.9em;
}

:deep(.markdown-content blockquote) {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  margin: 16px 0;
  color: #6a737d;
}

:deep(.markdown-content ul),
:deep(.markdown-content ol) {
  padding-left: 24px;
  margin: 12px 0;
}

:deep(.markdown-content li) {
  margin: 4px 0;
}

:deep(.markdown-content table) {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

:deep(.markdown-content table th),
:deep(.markdown-content table td) {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
}

:deep(.markdown-content table th) {
  background: #f6f8fa;
  font-weight: 600;
}

:deep(.markdown-content a) {
  color: #0366d6;
  text-decoration: none;
}

:deep(.markdown-content a:hover) {
  text-decoration: underline;
}

:deep(.markdown-content img) {
  max-width: 100%;
  height: auto;
  margin: 16px 0;
}

:deep(.markdown-content hr) {
  border: none;
  border-top: 2px solid #eaecef;
  margin: 24px 0;
}
</style>

